package com.jiyun.controller;

import java.util.Arrays;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationOutput;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@RequestMapping("ai")
public class AiController {

    private final Generation gen = new Generation();
    @PostMapping("/dog")
    public String callWithMessage(@RequestBody String question) {
        // 构建用户消息
        Message userMsg = Message.builder()
                .role("user")
                .content(question)  // 确保这里传递了有效的内容
                .build();

        // 构建参数
        GenerationParam param = GenerationParam.builder()
                .apiKey("sk-30db4a4ac1af428e8c96d281dad0312c")
                .model("qwen-max")
                .messages(Arrays.asList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();

        // 调用 API 并获取结果
        try {
            GenerationResult result = gen.call(param);
            GenerationOutput output = result.getOutput();
            return output.getChoices().get(0).getMessage().getContent();
        } catch (Exception e) {
            e.printStackTrace();
            return "API 调用失败，请检查输入内容";
        }
    }
}